<template>
  <div class="algorithm-list">
    <div class="header">
      <h3>AI算法管理</h3>
      <div class="actions">
        <el-button type="primary" @click="refreshList" :loading="loading">刷新</el-button>
        <el-button type="success" @click="startAllServices">启动所有服务</el-button>
        <el-button type="danger" @click="stopAllServices">停止所有服务</el-button>
      </div>
    </div>
    
    <div class="filters">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-select v-model="filters.status" placeholder="状态筛选" clearable>
            <el-option label="全部" value=""></el-option>
            <el-option label="运行中" value="running"></el-option>
            <el-option label="已停止" value="inactive"></el-option>
          </el-select>
        </el-col>
        <el-col :span="6">
          <el-select v-model="filters.type" placeholder="服务类型" clearable>
            <el-option label="全部" value=""></el-option>
            <el-option 
              v-for="(name, key) in serviceTypes" 
              :key="key" 
              :label="name" 
              :value="key">
            </el-option>
          </el-select>
        </el-col>
        <el-col :span="8">
          <el-input 
            v-model="filters.search" 
            placeholder="搜索算法名称"
            clearable>
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="handleSearch">搜索</el-button>
        </el-col>
      </el-row>
    </div>

    <!-- 统计信息 -->
    <div class="statistics">
      <el-row :gutter="20">
        <el-col :span="6">
          <div class="stat-card">
            <div class="stat-number">{{ statistics.totalAlgorithms }}</div>
            <div class="stat-label">总算法数</div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-card running">
            <div class="stat-number">{{ statistics.runningAlgorithms }}</div>
            <div class="stat-label">运行中</div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-card inactive">
            <div class="stat-number">{{ statistics.inactiveAlgorithms }}</div>
            <div class="stat-label">已停止</div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-card accuracy">
            <div class="stat-number">{{ statistics.avgAccuracy }}%</div>
            <div class="stat-label">平均准确率</div>
          </div>
        </el-col>
      </el-row>
    </div>

    <div class="algorithm-cards">
      <div v-if="loading" class="loading">
        <el-skeleton :rows="5" animated />
      </div>
      
      <div v-else-if="groupedAlgorithms.length === 0" class="empty">
        <el-empty description="暂无算法数据" />
      </div>
      
      <div v-else>
        <div 
          v-for="group in groupedAlgorithms" 
          :key="group.serviceId" 
          class="service-group">
          <div class="service-header">
            <div class="service-info">
              <h4>{{ group.serviceName }}</h4>
              <div class="service-stats">
                <span class="running">运行中: {{ group.runningCount }}</span>
                <span class="total">总计: {{ group.algorithms.length }}</span>
              </div>
            </div>
            <div class="service-actions">
              <el-button 
                type="success" 
                size="small"
                @click="startService(group.serviceId)">
                启动服务
              </el-button>
              <el-button 
                type="danger" 
                size="small"
                @click="stopService(group.serviceId)">
                停止服务
              </el-button>
            </div>
          </div>
          
          <div class="algorithms-grid">
            <div 
              v-for="algorithm in group.algorithms" 
              :key="algorithm.id"
              class="algorithm-card"
              :class="{ 'running': algorithm.status === 'running' }">
              <div class="card-header">
                <h5>{{ algorithm.name }}</h5>
                <el-tag 
                  :type="algorithm.status === 'running' ? 'success' : 'info'"
                  size="small">
                  {{ algorithm.status === 'running' ? '运行中' : '已停止' }}
                </el-tag>
              </div>
              
              <div class="card-content">
                <p class="description">{{ algorithm.description }}</p>
                <div class="stats">
                  <div class="stat-item">
                    <span class="label">准确率:</span>
                    <span class="value">{{ algorithm.accuracy }}%</span>
                  </div>
                  <div class="stat-item">
                    <span class="label">处理帧数:</span>
                    <span class="value">{{ formatNumber(algorithm.processedFrames) }}</span>
                  </div>
                  <div class="stat-item">
                    <span class="label">版本:</span>
                    <span class="value">{{ algorithm.version }}</span>
                  </div>
                </div>
              </div>
              
              <div class="card-actions">
                <el-button 
                  v-if="algorithm.status !== 'running'"
                  type="success" 
                  size="small"
                  :loading="algorithm.loading"
                  @click="startAlgorithm(algorithm)">
                  启动
                </el-button>
                <el-button 
                  v-else
                  type="danger" 
                  size="small"
                  :loading="algorithm.loading"
                  @click="stopAlgorithm(algorithm)">
                  停止
                </el-button>
                <el-button 
                  type="primary" 
                  size="small"
                  @click="configAlgorithm(algorithm)">
                  配置
                </el-button>
                <el-button 
                  type="info" 
                  size="small"
                  @click="viewDetails(algorithm)">
                  详情
                </el-button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="pagination" v-if="total > 0">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 算法详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="算法详情"
      width="600px">
      <div v-if="selectedAlgorithm" class="algorithm-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="算法名称">{{ selectedAlgorithm.name }}</el-descriptions-item>
          <el-descriptions-item label="所属服务">{{ selectedAlgorithm.service_name }}</el-descriptions-item>
          <el-descriptions-item label="算法类型">{{ selectedAlgorithm.algorithm_type }}</el-descriptions-item>
          <el-descriptions-item label="版本">{{ selectedAlgorithm.version }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="selectedAlgorithm.status === 'running' ? 'success' : 'info'">
              {{ selectedAlgorithm.status === 'running' ? '运行中' : '已停止' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="准确率">{{ selectedAlgorithm.accuracy }}%</el-descriptions-item>
          <el-descriptions-item label="处理帧数">{{ formatNumber(selectedAlgorithm.processedFrames) }}</el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ formatDateTime(selectedAlgorithm.created_at) }}</el-descriptions-item>
          <el-descriptions-item label="更新时间" :span="2">{{ formatDateTime(selectedAlgorithm.updated_at) }}</el-descriptions-item>
          <el-descriptions-item label="描述" :span="2">{{ selectedAlgorithm.description }}</el-descriptions-item>
        </el-descriptions>
        
        <div class="config-section" style="margin-top: 20px;">
          <h4>配置信息</h4>
          <el-descriptions :column="1" border>
            <el-descriptions-item label="置信度阈值">{{ selectedAlgorithm.config?.confidence_threshold || 0.7 }}</el-descriptions-item>
            <el-descriptions-item label="检测间隔">{{ selectedAlgorithm.config?.detection_interval || 5 }}秒</el-descriptions-item>
            <el-descriptions-item label="最大检测数">{{ selectedAlgorithm.config?.max_detections || 10 }}</el-descriptions-item>
          </el-descriptions>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import * as aiAlgorithmAPI from '@/api/ai-algorithm'

// 解构需要的函数
const getAlgorithms = aiAlgorithmAPI.getAlgorithmList
const apiStartAlgorithm = aiAlgorithmAPI.startAlgorithm
const apiStopAlgorithm = aiAlgorithmAPI.stopAlgorithm
const getAlgorithmStatistics = aiAlgorithmAPI.getAlgorithmStatistics

// 响应式数据
const loading = ref(false)
const algorithms = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(50)
const detailDialogVisible = ref(false)
const selectedAlgorithm = ref(null)

// 统计信息
const statistics = ref({
  totalAlgorithms: 0,
  runningAlgorithms: 0,
  inactiveAlgorithms: 0,
  avgAccuracy: 0
})

// 筛选条件
const filters = reactive({
  status: '',
  type: '',
  search: ''
})

// 服务类型映射 - 六大AI服务
const serviceTypes = {
  'campus_behavior_monitoring': '校园行为监控',
  'campus_crowd_safety': '校园人群安全',
  'campus_energy_management': '校园能源管理',
  'campus_environment_hygiene': '校园环境卫生',
  'intelligent_classroom_quality': '智能课堂质量',
  'teaching_quality_assessment': '教学质量评估'
}

// 计算属性 - 按服务分组的算法
const groupedAlgorithms = computed(() => {
  const groups = {}
  
  algorithms.value.forEach(algorithm => {
    const serviceId = algorithm.type
    const serviceName = algorithm.service_name || serviceTypes[serviceId] || serviceId
    
    if (!groups[serviceId]) {
      groups[serviceId] = {
        serviceId,
        serviceName,
        algorithms: [],
        runningCount: 0
      }
    }
    
    groups[serviceId].algorithms.push(algorithm)
    if (algorithm.status === 'running') {
      groups[serviceId].runningCount++
    }
  })
  
  // 按预定义的服务顺序排序
  const serviceOrder = [
    'campus_behavior_monitoring',
    'campus_crowd_safety', 
    'campus_energy_management',
    'campus_environment_hygiene',
    'intelligent_classroom_quality',
    'teaching_quality_assessment'
  ]
  
  const sortedGroups = []
  serviceOrder.forEach(serviceId => {
    if (groups[serviceId]) {
      sortedGroups.push(groups[serviceId])
    }
  })
  
  // 添加其他未分类的服务
  Object.values(groups).forEach(group => {
    if (!serviceOrder.includes(group.serviceId)) {
      sortedGroups.push(group)
    }
  })
  
  return sortedGroups
})

// 工具方法
const formatNumber = (num) => {
  if (num === undefined || num === null || isNaN(num)) {
    return '0'
  }
  const numValue = Number(num)
  if (numValue >= 1000) {
    return (numValue / 1000).toFixed(1) + 'K'
  }
  return numValue.toString()
}

const formatDateTime = (dateStr) => {
  if (!dateStr) return '-'
  return new Date(dateStr).toLocaleString('zh-CN')
}

// 方法
const loadAlgorithms = async () => {
  loading.value = true
  try {
    const params = {
      page: currentPage.value,
      size: pageSize.value,
      ...filters
    }
    
    console.log('🔄 加载算法列表，参数:', params)
    const response = await getAlgorithms(params)
    console.log('📊 API响应:', response)
    
    if (response.code === 200) {
      algorithms.value = response.rows || []
      total.value = response.total || 0
      
      console.log(`✅ 成功加载 ${algorithms.value.length} 个算法`)
      
      // 更新统计信息
      updateStatistics()
    } else {
      ElMessage.error(response.msg || '获取算法列表失败')
    }
  } catch (error) {
    console.error('❌ 获取算法列表失败:', error)
    ElMessage.error('获取算法列表失败')
  } finally {
    loading.value = false
  }
}

const loadStatistics = async () => {
  try {
    const response = await getAlgorithmStatistics()
    if (response.code === 200) {
      statistics.value = response.data
    }
  } catch (error) {
    console.error('获取统计信息失败:', error)
  }
}

const updateStatistics = () => {
  const total = algorithms.value.length
  const running = algorithms.value.filter(alg => alg.status === 'running').length
  const inactive = total - running
  const avgAccuracy = total > 0 ? 
    algorithms.value.reduce((sum, alg) => sum + (alg.accuracy || 0), 0) / total : 0
  
  statistics.value = {
    totalAlgorithms: total,
    runningAlgorithms: running,
    inactiveAlgorithms: inactive,
    avgAccuracy: Math.round(avgAccuracy * 10) / 10
  }
}

const refreshList = () => {
  loadAlgorithms()
  loadStatistics()
}

const handleSearch = () => {
  currentPage.value = 1
  loadAlgorithms()
}

const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
  loadAlgorithms()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  loadAlgorithms()
}

const startAlgorithm = async (algorithm) => {
  algorithm.loading = true
  try {
    const response = await apiStartAlgorithm(algorithm.id)
    if (response.code === 200) {
      ElMessage.success('算法启动成功')
      algorithm.status = 'running'
      updateStatistics()
    } else {
      ElMessage.error(response.msg || '启动失败')
    }
  } catch (error) {
    console.error('启动算法失败:', error)
    ElMessage.error('启动算法失败')
  } finally {
    algorithm.loading = false
  }
}

const stopAlgorithm = async (algorithm) => {
  try {
    await ElMessageBox.confirm('确定要停止该算法吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    algorithm.loading = true
    const response = await apiStopAlgorithm(algorithm.id)
    if (response.code === 200) {
      ElMessage.success('算法停止成功')
      algorithm.status = 'inactive'
      updateStatistics()
    } else {
      ElMessage.error(response.msg || '停止失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('停止算法失败:', error)
      ElMessage.error('停止算法失败')
    }
  } finally {
    algorithm.loading = false
  }
}

const startService = async (serviceId) => {
  try {
    const response = await apiStartAlgorithm(serviceId)
    if (response.code === 200) {
      ElMessage.success('服务启动成功')
      // 更新该服务下所有算法的状态
      algorithms.value.forEach(alg => {
        if (alg.type === serviceId) {
          alg.status = 'running'
        }
      })
      updateStatistics()
    } else {
      ElMessage.error(response.msg || '服务启动失败')
    }
  } catch (error) {
    console.error('启动服务失败:', error)
    ElMessage.error('启动服务失败')
  }
}

const stopService = async (serviceId) => {
  try {
    await ElMessageBox.confirm('确定要停止该服务下的所有算法吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const response = await apiStopAlgorithm(serviceId)
    if (response.code === 200) {
      ElMessage.success('服务停止成功')
      // 更新该服务下所有算法的状态
      algorithms.value.forEach(alg => {
        if (alg.type === serviceId) {
          alg.status = 'inactive'
        }
      })
      updateStatistics()
    } else {
      ElMessage.error(response.msg || '服务停止失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('停止服务失败:', error)
      ElMessage.error('停止服务失败')
    }
  }
}

const startAllServices = async () => {
  try {
    await ElMessageBox.confirm('确定要启动所有算法服务吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const serviceIds = Object.keys(serviceTypes)
    for (const serviceId of serviceIds) {
      await apiStartAlgorithm(serviceId)
    }
    
    ElMessage.success('所有服务启动成功')
    algorithms.value.forEach(alg => {
      alg.status = 'running'
    })
    updateStatistics()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('启动所有服务失败:', error)
      ElMessage.error('启动所有服务失败')
    }
  }
}

const stopAllServices = async () => {
  try {
    await ElMessageBox.confirm('确定要停止所有算法服务吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const serviceIds = Object.keys(serviceTypes)
    for (const serviceId of serviceIds) {
      await apiStopAlgorithm(serviceId)
    }
    
    ElMessage.success('所有服务停止成功')
    algorithms.value.forEach(alg => {
      alg.status = 'inactive'
    })
    updateStatistics()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('停止所有服务失败:', error)
      ElMessage.error('停止所有服务失败')
    }
  }
}

const configAlgorithm = (algorithm) => {
  ElMessage.info('算法配置功能开发中...')
}

const viewDetails = (algorithm) => {
  selectedAlgorithm.value = algorithm
  detailDialogVisible.value = true
}

// 生命周期
onMounted(() => {
  loadAlgorithms()
  loadStatistics()
})
</script>

<style scoped>
.algorithm-list {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header h3 {
  margin: 0;
  color: #303133;
  font-size: 24px;
  font-weight: 600;
}

.actions {
  display: flex;
  gap: 10px;
}

.filters {
  margin-bottom: 20px;
  padding: 20px;
  background: #f5f7fa;
  border-radius: 8px;
}

.statistics {
  margin-bottom: 20px;
}

.stat-card {
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  text-align: center;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  border-left: 4px solid #409eff;
  transition: transform 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-2px);
}

.stat-card.running {
  border-left-color: #67c23a;
}

.stat-card.inactive {
  border-left-color: #909399;
}

.stat-card.accuracy {
  border-left-color: #e6a23c;
}

.stat-number {
  font-size: 28px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 8px;
}

.stat-label {
  font-size: 14px;
  color: #606266;
}

.algorithm-cards {
  min-height: 400px;
}

.loading, .empty {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 400px;
}

.service-group {
  margin-bottom: 30px;
}

.service-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border-radius: 8px 8px 0 0;
  margin-bottom: 0;
}

.service-info h4 {
  margin: 0 0 5px 0;
  font-size: 18px;
  font-weight: 600;
}

.service-stats {
  display: flex;
  gap: 15px;
}

.service-stats span {
  font-size: 14px;
  opacity: 0.9;
}

.service-actions {
  display: flex;
  gap: 10px;
}

.algorithms-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
  gap: 20px;
  padding: 20px;
  background: #fff;
  border: 1px solid #e4e7ed;
  border-top: none;
  border-radius: 0 0 8px 8px;
}

.algorithm-card {
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  padding: 20px;
  background: #fff;
  transition: all 0.3s ease;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.algorithm-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.algorithm-card.running {
  border-left: 4px solid #67c23a;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.card-header h5 {
  margin: 0;
  color: #303133;
  font-size: 16px;
  font-weight: 600;
}

.card-content {
  margin-bottom: 20px;
}

.description {
  color: #606266;
  font-size: 14px;
  margin-bottom: 15px;
  line-height: 1.5;
}

.stats {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 10px;
}

.stat-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  text-align: center;
}

.stat-item .label {
  font-size: 12px;
  color: #909399;
  margin-bottom: 4px;
}

.stat-item .value {
  font-size: 14px;
  font-weight: 600;
  color: #303133;
}

.card-actions {
  display: flex;
  gap: 8px;
  justify-content: flex-end;
  flex-wrap: wrap;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.algorithm-detail {
  max-height: 500px;
  overflow-y: auto;
}

.config-section h4 {
  margin: 0 0 10px 0;
  color: #303133;
  font-size: 16px;
}
</style>